package com.xoa.service.party;


import com.xoa.dao.party.EnDoorThreeMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.EnDoorThree;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by gsb on 2018/1/9.
 */
@Service
public class EnDoorThreeService {
    @Resource
    private EnDoorThreeMapper enDoorThreeMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;

    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:10:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> insertSelective(EnDoorThree enDoorThree, HttpServletRequest request, String gridLocation){
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            if(gridLocation!=null){
                enDoorThree.setT1(gridLocation);
            }
            enDoorThree.setCreateUser(user.getUserId());
            enDoorThree.setCreaeteTime(DateFormat.getDatestr(new Date()));
            enDoorThreeMapper.insertSelective(enDoorThree);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:10:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> deleteByPrimaryKey(Integer tid){
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            enDoorThreeMapper.deleteByPrimaryKey(tid);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:20:51
     * 类介绍  :  修改
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> updateByPrimaryKeySelective(EnDoorThree enDoorThree, String gridLocation){
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            if(gridLocation!=null){
                enDoorThree.setT1(gridLocation);
            }
            enDoorThreeMapper.updateByPrimaryKeySelective(enDoorThree);
            json.setFlag(0);
            json.setMsg("true");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:20:51
     * 类介绍  :  详情
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> selectById(Integer tid) {
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            EnDoorThree enDoorThree = enDoorThreeMapper.selectById(tid);
            json.setObject(enDoorThree);
            json.setFlag(0);
            json.setMsg("true");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }




    public ToJson<EnDoorThree> selectByList(EnDoorThree enDoorThree, Integer page, Integer pageSize,
                                            boolean useFlag, HttpServletRequest request, HttpServletResponse response){
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
           map.put("page", pageParams);
            map.put("t1",enDoorThree.getT1());
            List<EnDoorThree> enDoorThreeList = enDoorThreeMapper.selectByList(map);

            String jutiAddtrss=mapOwnerinfoMapper.selectByLabelName(enDoorThree.getT1());

            enDoorThreeList.get(0).setJutiAddress(jutiAddtrss);

            if (enDoorThreeList!=null&&enDoorThreeList.size()>0){
                for (EnDoorThree enDoorThree1:enDoorThreeList){
                    if ("1".equals(enDoorThree1.getBusinessLicense())){
                        enDoorThree1.setBusinessLicense("有");
                    }else if ("0".equals(enDoorThree1.getBusinessLicense())){
                        enDoorThree1.setBusinessLicense("无");
                    }else {
                        enDoorThree1.setBusinessLicense("");
                    }
                    if ("1".equals(enDoorThree1.getSanitationLicense())){
                        enDoorThree1.setSanitationLicense("有");
                    }else if ("0".equals(enDoorThree1.getSanitationLicense())){
                        enDoorThree1.setSanitationLicense("无");
                    }else {
                        enDoorThree1.setSanitationLicense("");
                    }
                    if ("1".equals(enDoorThree1.getResponsibility())){
                        enDoorThree1.setResponsibility("是");
                    }else  if ("0".equals(enDoorThree1.getResponsibility())){
                        enDoorThree1.setResponsibility("否");
                    }else {
                        enDoorThree1.setResponsibility("");
                    }

                }
            }
            json.setTotleNum(enDoorThreeMapper.selectCount(enDoorThree));
            json.setObj(enDoorThreeList);
            json.setFlag(0);
            json.setMsg("ok");
          }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }


    public ToJson<EnDoorThree> queryByList() {
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
           List<EnDoorThree> enDoorThree = enDoorThreeMapper.queryByList();
            json.setObject(enDoorThree);
            json.setFlag(0);
            json.setMsg("true");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:25:51
     * 类介绍  : 列表  查询 导出
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> queryList(EnDoorThree enDoorThree, Integer page, Integer pageSize,
                                         boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export){
        ToJson<EnDoorThree> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enDoorThree",enDoorThree);
            if(export==null){
                export="0";
            }
            List<EnDoorThree> enDoorThreeList = enDoorThreeMapper.selectList(map);
            if (enDoorThreeList!=null&&enDoorThreeList.size()>0){
                for (EnDoorThree enDoorThree1:enDoorThreeList){
                    if ("1".equals(enDoorThree1.getBusinessLicense())){
                        enDoorThree1.setBusinessLicense("有");
                    }else if ("0".equals(enDoorThree1.getBusinessLicense())){
                        enDoorThree1.setBusinessLicense("无");
                    }else {
                        enDoorThree1.setBusinessLicense("");
                    }
                    if ("1".equals(enDoorThree1.getSanitationLicense())){
                        enDoorThree1.setSanitationLicense("有");
                    }else if ("0".equals(enDoorThree1.getSanitationLicense())){
                        enDoorThree1.setSanitationLicense("无");
                    }else {
                        enDoorThree1.setSanitationLicense("");
                    }
                    if ("1".equals(enDoorThree1.getResponsibility())){
                        enDoorThree1.setResponsibility("是");
                    }else  if ("0".equals(enDoorThree1.getResponsibility())){
                        enDoorThree1.setResponsibility("否");
                    }else {
                        enDoorThree1.setResponsibility("");
                    }

                }
            }
            json.setObj(enDoorThreeList);
            json.setTotleNum(enDoorThreeMapper.selectCount(enDoorThree));
            json.setFlag(0);
            json.setMsg("ok");
            if (export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("门前三包信息", 22);
                String[] secondTitles = {"社区", "名称", "地址", "经营类型", "有无营业执照","有无卫生许可证",
                        "是否张贴门前三包责任书","牌匾名称","经营者姓名","联系电话","备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"grid", "name", "address", "businessType", "businessLicense", "sanitationLicense",
                        "responsibility","plaqueName","operatorName","phoneNumber","note6"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, enDoorThreeList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "门前三包账信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();

            }
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 下午12:40:51
     * 类介绍  : 导入
     * 构造参数:
     *
     */
    public ToJson<EnDoorThree> importEnDoorThree(MultipartFile file, HttpServletResponse response,
                                                 HttpServletRequest request, HttpSession session) {
        ToJson<EnDoorThree> json = new ToJson<>();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
//                    String readPath = path.append(fileName).toString();
//                    String readPath = file.getInputStream();
                    InputStream in =  file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    EnDoorThree enDoorThree = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        enDoorThree = new EnDoorThree();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null ) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null ) {
                                    switch (j) {
                                        case 0:
                                            //社区
                                           enDoorThree.setGrid(cell.getStringCellValue());
                                           break;
                                        case 1:
                                            //名称
                                            enDoorThree.setName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //地址
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enDoorThree.setAddress(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //经营类型
                                            enDoorThree.setBusinessType(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //有无营业执照
                                            if ("有".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setBusinessLicense("1");
                                            }else if ("无".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setBusinessLicense("0");
                                            }else {
                                            enDoorThree.setBusinessLicense("");
                                            }
                                            break;
                                        case 5:
                                            //有无卫生许可证
                                            if ("有".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setSanitationLicense("1");
                                            }else if ("无".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setSanitationLicense("0");
                                            }else {
                                                enDoorThree.setSanitationLicense("");
                                            }
                                            break;
                                        case 6:
                                            //是否张贴门前三包责任书
                                            if ("是".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setResponsibility("1");
                                            }else if ("否".equals(cell.getStringCellValue().trim())){
                                                enDoorThree.setResponsibility("0");
                                            }else {
                                                enDoorThree.setResponsibility("");
                                            }
                                            break;
                                        case 7:
                                            //牌匾名称
                                            enDoorThree.setPlaqueName(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //经营者姓名
                                            enDoorThree.setOperatorName(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            //联系电话
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enDoorThree.setPhoneNumber(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //备注
                                            enDoorThree.setNote6(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            enDoorThree.setT1(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            enDoorThree.setCreateUser(users.getUserId());
                            enDoorThree.setCreaeteTime(DateFormat.getCurrentTime());
                            //将数据放入数据库
                            int count=enDoorThreeMapper.insertSelective(enDoorThree);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                json.setTotleNum(successCount);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setTotleNum(successCount+1);
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    }
